#include <QPainter>
#include <QPixmap>
#include <QFileInfo>
#include <QMessageBox>
#include <QFileDialog>
#include <QDateTime>
#include <QProgressDialog>
#include <QApplication>
#include <QThread>
#include <QStandardPaths>
#include <QTabWidget>
#include <QFutureWatcher>
#include <QFuture>
#include <QObject>
#include <QTextStream>
#include <QVector>
#include "desktop.h"
#include "dataspecification.h"
#include "ae/aeampspectrum.h"
#include <QtConcurrent/QtConcurrent>
#include "exporter/spectrumexporter.h"
#include <QDesktopServices>
#include <QDir>
#include <QTimer>
#include <QEventLoop>
#include "exporter/progressdialog.h"
//局部宏定义
#define BACKGROUND_PNG          ":/resource/images/background/background_2.png" //背景图片
#define WINDOW_WIDTH 1200
#define WINDOW_HEIGHT 800
Desktop::Desktop(QWidget *parent)
    : QMainWindow{parent}
    ,specification{new DataSpecificationGW::DataSpecification}
    ,m_infoPrint{InfoPrint::instance(this)}
    ,m_tabFrame{new TabWidgetFrame(this)}
    ,m_functionBtn{new FunctionButton(this)}

{
    this->resize(WINDOW_WIDTH,WINDOW_HEIGHT);
    this->setWindowTitle("国网协议解析工具");
    this->setStyleSheet("QFrame{background-image:url(:/resource/images/background/background_2.png)}");

    InitTabWidget();
    InitInfoPrint();
    InitFuncBtn();
    DebugLogPrint("I Love You");
}


Desktop::~Desktop()
{
    delete specification;
    delete m_tabFrame;
    delete m_functionBtn;
    delete m_mainLayout;
}

void Desktop::onFileSelected(QString filePath)
{
    // 验证文件
    if (!validateFile(filePath)) {
        return;
    }
    
    // 保存当前文件路径
    m_currentFilePath = filePath;
    InfoLogPrint(QString("加载文件: %1").arg(QDir::toNativeSeparators(filePath)));
    
    // 创建进度对话框
    ProgressDialog* progress = new ProgressDialog(tr("正在加载文件..."), this);
    progress->setShowCancelButton(true);
    progress->setProgressStyle(
        "QProgressBar {"
        "    border: 2px solid #2196F3;"
        "    border-radius: 5px;"
        "    text-align: center;"
        "    background-color: #E3F2FD;"
        "}"
        "QProgressBar::chunk {"
        "    background-color: #2196F3;"
        "    border-radius: 3px;"
        "}"
    );
    progress->setWindowStyle(
        "QDialog {"
        "    background-color: white;"
        "    border: 1px solid #BDBDBD;"
        "    border-radius: 8px;"
        "}"
        "QLabel {"
        "    color: #212121;"
        "}"
        "QPushButton {"
        "    background-color: #2196F3;"
        "    color: white;"
        "    border: none;"
        "    border-radius: 4px;"
        "    padding: 5px 15px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #1976D2;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #0D47A1;"
        "}"
    );
    
    // 创建数据规范对象
    DataSpecificationGW::DataSpecification* specification = new DataSpecificationGW::DataSpecification();
    
    // 创建导出器
    SpectrumExporter* exporter = SpectrumExporter::instance();
    
    // 连接进度信号
    connect(exporter, &SpectrumExporter::progressUpdated,
            progress, &ProgressDialog::setValue);
    
    // 连接取消信号
//    connect(progress, &ProgressDialog::canceled,
//            specification, &DataSpecificationGW::DataSpecification::cancel);
    
    // 使用QtConcurrent运行加载任务
    QFuture<bool> future = QtConcurrent::run([filePath, specification]() {
        try {
            InfoLogPrint(QString("正在加载文件: %1").arg(QDir::toNativeSeparators(filePath)));
            return specification->parseBinaryFromFile(filePath, true);
        } catch (const std::exception& e) {
            ErrorLogPrint(QString("加载文件异常: %1").arg(e.what()));
            return false;
        }
    });
    
    // 创建FutureWatcher
    QFutureWatcher<bool>* watcher = new QFutureWatcher<bool>(this);
    watcher->setFuture(future);
    
    // 连接完成信号
    connect(watcher, &QFutureWatcher<bool>::finished, this, [=]() {
        bool success = watcher->result();
        if (success) {
            // 处理加载成功
            handleLoadSuccess(specification);
        } else {
            // 处理加载失败
            handleLoadError();
        }
        
        // 清理资源
        watcher->deleteLater();
        progress->deleteLater();
    });
    
    // 显示进度对话框
    progress->show();
}

void Desktop::onRecentFileSelected(QString filePath)
{
    // 调用通用文件加载方法
    onFileSelected(filePath);
}

void Desktop::onClearAll()
{
    // 如果没有数据，则直接返回
    if (m_currentFilePath.isEmpty()) {
        QMessageBox::information(this, tr("清空数据"), tr("当前没有加载任何数据文件。"));
        return;
    }
    
    // 显示确认对话框
    QMessageBox::StandardButton result = QMessageBox::question(
        this, tr("确认清空"), tr("确定要清空当前所有数据吗？此操作无法撤销。"),
        QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    
    if (result != QMessageBox::Yes) {
        return;
    }
    
    // 创建进度对话框
    QProgressDialog progress(tr("正在清空数据..."), tr("取消"), 0, 100, this);
    progress.setWindowModality(Qt::WindowModal);
    progress.setCancelButton(nullptr); // 禁用取消按钮
    progress.setMinimumDuration(0);
    progress.setValue(10);

    // 使用QtConcurrent异步处理清空操作
    QFutureWatcher<void>* watcher = new QFutureWatcher<void>();
    
    connect(watcher, &QFutureWatcher<void>::finished, this, [this, watcher] {

        
        // 清空路径
        m_currentFilePath.clear();
        
        // 更新按钮状态
        m_functionBtn->setButtonsEnabled(false);
        m_functionBtn->enableOpenButton(true);

        InfoLogPrint("数据已清空");
        
        watcher->deleteLater();
    });
    
    QFuture<void> future = QtConcurrent::run([this, &progress] {
        // 设置进度
        QMetaObject::invokeMethod(&progress, "setValue", Qt::QueuedConnection, Q_ARG(int, 30));
        
        // 清空数据规范对象
        if (specification) {
            delete specification;
            specification = new DataSpecificationGW::DataSpecification();
        }
        
        // 设置进度
        QMetaObject::invokeMethod(&progress, "setValue", Qt::QueuedConnection, Q_ARG(int, 70));
        
        // 给UI一些时间更新进度
        QThread::msleep(200);
    });
    
    watcher->setFuture(future);
    progress.exec();
}

void Desktop::onRefresh()
{
    InfoLogPrint("刷新视图");
    
    // 设置鼠标为等待状态
    QApplication::setOverrideCursor(Qt::WaitCursor);
    
    // TODO: 实现具体的刷新逻辑
    
    // 恢复鼠标状态
    QApplication::restoreOverrideCursor();
}

void Desktop::onExport()
{
    if (!specification) {
        QMessageBox::warning(this, "警告", "没有数据可导出");
        return;
    }
    
    QString fileName = QFileDialog::getSaveFileName(this, "导出文件",
                                                   QDir::homePath(),
                                                   "CSV文件 (*.csv);;Excel文件 (*.xlsx);;JSON文件 (*.json);;XML文件 (*.xml)");
    
    if (fileName.isEmpty()) {
        return; // 用户取消
    }
    
    QFileInfo fileInfo(fileName);
    QString suffix = fileInfo.suffix().toLower();
    
    SpectrumExporter::ExportFormat format = SpectrumExporter::CSV;
    
    if (suffix == "csv") {
        format = SpectrumExporter::CSV;
    } else if (suffix == "xlsx") {
        format = SpectrumExporter::EXCEL;
    } else if (suffix == "json") {
        format = SpectrumExporter::JSON;
    } else if (suffix == "xml") {
        format = SpectrumExporter::XML;
    }
    
    // 创建并配置导出选项
    SpectrumExporter::ExportOptions options;
    options.addBOM = true;
    options.exportFileHeader = true;
    options.exportSpectrumBasicInfo = true;
    options.exportSpectrumExtInfo = true;
    options.binaryOption = SpectrumExporter::HEXSTRING_SHORT;
    
    // 导出文件
    bool success = SpectrumExporter::instance()->exportToFile(fileName, specification, format, options);
    
    if (success) {
        QMessageBox::information(this, "导出成功", QString("文件已成功导出到: %1").arg(fileName));
    } else {
        QMessageBox::critical(this, "导出失败", "导出文件时发生错误");
    }
}


void Desktop::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);  // 标记参数为未使用，避免警告
    // 绘制桌面背景
    QPainter painter(this);
    painter.fillRect(rect(), palette().window());
}


void Desktop::InitTabWidget()
{
    m_tabFrame->move(0,0);
    m_tabFrame->resize(WINDOW_WIDTH-10,WINDOW_HEIGHT*0.8-5);
    m_tabFrame->setFixedSize(WINDOW_WIDTH-10,WINDOW_HEIGHT*0.8-5);
    m_tabFrame->show();
}

void Desktop::InitInfoPrint()
{
    m_infoPrint->move(5,WINDOW_HEIGHT*0.8);
    m_infoPrint->resize(WINDOW_WIDTH*0.6,WINDOW_HEIGHT*0.2-5);
    m_infoPrint->setFixedSize(WINDOW_WIDTH*0.6,WINDOW_HEIGHT*0.2-5);
    m_infoPrint->show();
}

void Desktop::InitFuncBtn()
{
    m_functionBtn->move(WINDOW_WIDTH*0.6,WINDOW_HEIGHT*0.8);
    m_functionBtn->resize(WINDOW_WIDTH*0.4,WINDOW_HEIGHT*0.2-5);
    m_functionBtn->setFixedSize(WINDOW_WIDTH*0.4,WINDOW_HEIGHT*0.2-5);
    m_functionBtn->show();
    
    // 连接信号和槽
    connect(m_functionBtn, &FunctionButton::sigFileSelected, this, &Desktop::onFileSelected);
    connect(m_functionBtn, &FunctionButton::sigClearAll, this, &Desktop::onClearAll);
    connect(m_functionBtn, &FunctionButton::sigRefresh, this, &Desktop::onRefresh);
    connect(m_functionBtn, &FunctionButton::sigExport, this, &Desktop::onExport);
    connect(m_functionBtn, &FunctionButton::sigRecentFileSelected, this, &Desktop::onRecentFileSelected);
}

bool Desktop::validateFile(const QString& filePath)
{
    if (filePath.isEmpty()) {
        return false;
    }
    
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists()) {
        QMessageBox::warning(this, tr("文件错误"), 
                           tr("文件不存在: %1").arg(QDir::toNativeSeparators(filePath)));
        return false;
    }
    
    if (!fileInfo.isReadable()) {
        QMessageBox::warning(this, tr("文件错误"), 
                           tr("文件无法读取: %1").arg(QDir::toNativeSeparators(filePath)));
        return false;
    }
    
    // 判断文件大小，避免打开过大的文件
    double fileSizeMB = fileInfo.size() / (1024.0 * 1024.0);
    if (fileSizeMB > 100) { // 超过100MB要提示用户
        auto response = QMessageBox::question(this, tr("大文件警告"), 
                            tr("文件大小超过100MB (%.2fMB)，打开可能需要较长时间。是否继续?").arg(fileSizeMB),
                            QMessageBox::Yes | QMessageBox::No, 
                            QMessageBox::No);
        if (response != QMessageBox::Yes) {
            return false;
        }
    }
    
    return true;
}

void Desktop::showProgress(const QString& title, int duration)
{
    QProgressDialog progress(title, tr("请稍候..."), 0, 100, this);
    progress.setWindowModality(Qt::WindowModal);
    progress.setMinimumDuration(0);
    progress.setCancelButton(nullptr); // 禁用取消按钮
    
    QTimer timer;
    QEventLoop loop;
    
    connect(&timer, &QTimer::timeout, [&progress, &loop]() {
        static int value = 0;
        value += 5;
        if (value > 100) {
            value = 100;
            loop.quit();
        }
        progress.setValue(value);
    });
    
    timer.start(duration / 20); // 分20步完成
    progress.show();
    loop.exec();
}

QString Desktop::getSaveFilePath(const QString& defaultName, const QString& filter)
{
    // 如果当前文件路径为空，则使用文档目录
    QString defaultDir = !m_currentFilePath.isEmpty() ?
        QFileInfo(m_currentFilePath).absolutePath() :
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    
    QString suggestedPath = defaultDir + "/" + defaultName;
    
    return QFileDialog::getSaveFileName(this, tr("保存文件"), suggestedPath, filter);
}

void Desktop::handleLoadSuccess(DataSpecificationGW::DataSpecification* specification)
{
    InfoLogPrint("文件加载成功");
    
    DataSpecificationGW::SpectrumDataFileHead stSpectrumDataFileHead;
    specification->getSpectrumDataFileHead(stSpectrumDataFileHead);
    m_tabFrame->setTabHeadChart(stSpectrumDataFileHead);

    InfoLogPrint(QString("文件包含 %1 个图谱").arg(stSpectrumDataFileHead.sSpectrumCount));
    // 加载所有图谱
    for (int var = 0; var < stSpectrumDataFileHead.sSpectrumCount; ++var)
    {
        DataSpecificationGW::Spectrum* spectrum = specification->spectrum(var);
        if (spectrum) {
            m_tabFrame->setSpectrum(var, spectrum);
        }
    }
}

void Desktop::handleLoadError()
{
    QMessageBox::critical(this, tr("加载失败"), 
        tr("无法解析文件: \n请确保文件格式正确。"));
    ErrorLogPrint("文件解析失败");
    m_currentFilePath.clear();
}

void Desktop::saveFile()
{
    if (m_currentFilePath.isEmpty()) {
        QMessageBox::warning(this, tr("保存失败"), tr("没有打开的文件"));
        return;
    }

    // 获取保存文件路径
    QString savePath = getSaveFilePath();
    if (savePath.isEmpty()) {
        return;
    }

    // 创建进度对话框
    ProgressDialog* progress = new ProgressDialog(tr("正在保存文件..."), this);
    progress->setShowCancelButton(true);
    progress->setProgressStyle(
        "QProgressBar {"
        "    border: 2px solid #2196F3;"
        "    border-radius: 5px;"
        "    text-align: center;"
        "    background-color: #E3F2FD;"
        "}"
        "QProgressBar::chunk {"
        "    background-color: #2196F3;"
        "    border-radius: 3px;"
        "}"
    );
    progress->setWindowStyle(
        "QDialog {"
        "    background-color: white;"
        "    border: 1px solid #BDBDBD;"
        "    border-radius: 8px;"
        "}"
        "QLabel {"
        "    color: #212121;"
        "}"
        "QPushButton {"
        "    background-color: #2196F3;"
        "    color: white;"
        "    border: none;"
        "    border-radius: 4px;"
        "    padding: 5px 15px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #1976D2;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #0D47A1;"
        "}"
    );

    // 创建导出器
    SpectrumExporter* exporter = SpectrumExporter::instance();

    // 连接进度信号
    connect(exporter, &SpectrumExporter::progressUpdated,
            progress, &ProgressDialog::setValue);

    // 使用QtConcurrent运行保存任务
    QFuture<bool> future = QtConcurrent::run([savePath, exporter]() {
        try {
            InfoLogPrint(QString("正在保存文件: %1").arg(QDir::toNativeSeparators(savePath)));
            return exporter->exportToFile(savePath, nullptr, SpectrumExporter::CSV);
        } catch (const std::exception& e) {
            ErrorLogPrint(QString("保存文件异常: %1").arg(e.what()));
            return false;
        }
    });

    // 创建FutureWatcher
    QFutureWatcher<bool>* watcher = new QFutureWatcher<bool>(this);
    watcher->setFuture(future);

    // 连接完成信号
    connect(watcher, &QFutureWatcher<bool>::finished, this, [=]() {
        bool success = watcher->result();
        if (success) {
            InfoLogPrint(QString("文件保存成功: %1").arg(QDir::toNativeSeparators(savePath)));
            QMessageBox::information(this, tr("保存成功"), 
                tr("文件已成功保存到: %1").arg(QDir::toNativeSeparators(savePath)));
        } else {
            ErrorLogPrint(QString("文件保存失败: %1").arg(savePath));
            QMessageBox::critical(this, tr("保存失败"), 
                tr("无法保存文件: %1\n请确保有足够的磁盘空间和写入权限。")
                .arg(QDir::toNativeSeparators(savePath)));
        }

        // 清理资源
        watcher->deleteLater();
        progress->deleteLater();
    });

    // 显示进度对话框
    progress->show();
}

void Desktop::loadFile(const QString& filePath)
{
    if (filePath.isEmpty()) return;
    
    // 创建进度对话框
    ProgressDialog* progress = new ProgressDialog(tr("正在加载文件..."), this);
    progress->setShowCancelButton(true);
    progress->setProgressStyle(
        "QProgressBar {"
        "    border: 2px solid #2196F3;"
        "    border-radius: 5px;"
        "    text-align: center;"
        "    background-color: #E3F2FD;"
        "}"
        "QProgressBar::chunk {"
        "    background-color: #2196F3;"
        "    border-radius: 3px;"
        "}"
    );
    progress->setWindowStyle(
        "QDialog {"
        "    background-color: white;"
        "    border: 1px solid #BDBDBD;"
        "    border-radius: 8px;"
        "}"
        "QLabel {"
        "    color: #212121;"
        "}"
        "QPushButton {"
        "    background-color: #2196F3;"
        "    color: white;"
        "    border: none;"
        "    border-radius: 4px;"
        "    padding: 5px 15px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #1976D2;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #0D47A1;"
        "}"
    );
    
    // 创建数据规范对象
    DataSpecificationGW::DataSpecification* specification = new DataSpecificationGW::DataSpecification();
    
    // 创建导出器
    SpectrumExporter* exporter = SpectrumExporter::instance();
    
    // 连接进度信号
    connect(exporter, &SpectrumExporter::progressUpdated,
            progress, &ProgressDialog::setValue);
    
    // 连接取消信号
    connect(progress, &ProgressDialog::canceled, this, [=]() {
        // 清理资源
        delete specification;
        progress->deleteLater();
        InfoLogPrint("用户取消了文件加载");
    });
    
    // 使用QtConcurrent运行加载任务
    QFuture<bool> future = QtConcurrent::run([filePath, specification]() {
        try {
            InfoLogPrint(QString("正在加载文件: %1").arg(QDir::toNativeSeparators(filePath)));
            return specification->parseBinaryFromFile(filePath, true);
        } catch (const std::exception& e) {
            ErrorLogPrint(QString("加载文件异常: %1").arg(e.what()));
            return false;
        }
    });
    
    // 创建FutureWatcher
    QFutureWatcher<bool>* watcher = new QFutureWatcher<bool>(this);
    watcher->setFuture(future);
    
    // 连接完成信号
    connect(watcher, &QFutureWatcher<bool>::finished, this, [=]() {
        bool success = watcher->result();
        if (success) {
            // 处理加载成功
            handleLoadSuccess(specification);
        } else {
            // 处理加载失败
            handleLoadError();
        }
        
        // 清理资源
        watcher->deleteLater();
        progress->deleteLater();
    });
    
    // 显示进度对话框
    progress->show();
}

